import React, { useState } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    TextField,
    Box,
    Typography,
    Divider,
    IconButton,
    useTheme,
    useMediaQuery,
    Select,
    MenuItem,
    InputLabel
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import PersonAddAltIcon from '@mui/icons-material/PersonAddAlt';
import { StudentFormData } from '../type';

// 初始表单数据
const initialFormData: StudentFormData = {
    sid: '',
    name: '',
    college: '',
    major: '',
    grade: '',
    graduation_pre: '',
    graduation_year: '',
    phone: '',
    email: '',
    academic_advisor: '',
    academic_advisor_phone: '',
    state: '',
    emergency_contact: '',
    emergency_contact_phone: '',
    cgpa: '',
    credit: '',
    approach: '',
    warn_info: ''
};

// 表单字段配置
const getFormFields = (
    enrollmentStatusOptions: any,
    enrollmentTypeOptions: any,
    advisorOptions: any
) => [
    { id: 'sid', label: '学生ID', type: 'text', description: '学号ID', required: true },
    { id: 'name', label: '姓名', type: 'text', description: '姓名', required: false },
    { id: 'college', label: '书院', type: 'text', description: '书院', required: false },
    { id: 'major', label: '专业', type: 'text', description: '专业', required: false },
    { id: 'grade', label: '年级', type: 'text', description: '年级', required: false },
    { id: 'graduation_year', type: 'year-picker', label: '毕业年份', description: '毕业年份', required: false },
    { id: 'phone', label: '联系方式', type: 'text', description: '联系方式', required: false },
    { id: 'email', label: '邮箱', type: 'text', description: '邮箱', required: false },
    { id: 'academic_advisor', label: '职业导师', type: 'text', description: '职业导师', required: false },
    { id: 'academic_advisor_phone', label: '导师电话', description: '导师电话', required: false },
    {
        id: 'state',
        label: '学籍状态',
        type: 'select',
        description: '学籍状态',
        required: false,
        options:
            enrollmentStatusOptions.length > 0
                ? enrollmentStatusOptions.map((status) => ({ value: status, label: status }))
                : [
                    { value: '课程中有效', label: '课程中有效' },
                    { value: '休假', label: '休假' }
                ]
    },
    { id: 'emergency_contact', label: '紧急联系人', type: 'text', description: '紧急联系人', required: false },
    { id: 'emergency_contact_phone', label: '紧急联系电话', type: 'text', description: '紧急联系电话', required: false },
    { id: 'cgpa', label: '绩点', type: 'text', description: '绩点', required: false },
    { id: 'credit', label: '修分情况', type: 'text', description: '修分情况', required: false },
    {
        id: 'approach',
        label: '招生类型',
        type: 'select',
        description: '招生类型',
        required: false,
        options:
            enrollmentTypeOptions.length > 0
                ? enrollmentTypeOptions.map((type) => ({ value: type, label: type }))
                : [
                    { value: '高考学生（中国籍）', label: '高考学生（中国籍）' },
                    { value: '海本学生（中国籍）', label: '海本学生（中国籍）' },
                    { value: '国际生', label: '国际生' }
                ]
    },
    { id: 'warn_info', label: '预警信息', type: 'text', description: '预警信息', required: false },
    {
        id: 'advisor',
        label: '顾问',
        type: 'select',
        description: '顾问',
        required: false,
        options:
            advisorOptions.length > 0
                ? advisorOptions.map((advisor) => ({ value: advisor, label: advisor }))
                : [
                    { value: 'Maxine', label: 'Maxine' },
                    { value: 'Laila', label: 'Laila' },
                    { value: 'Zoey', label: 'Zoey' },
                    { value: 'Bella', label: 'Bella' },
                    { value: 'Mandy', label: 'Mandy' },
                    { value: 'Sherry', label: 'Sherry' },
                    { value: 'Ann', label: 'Ann' },
                    { value: 'Ashley', label: 'Ashley' }
                ]
    }
];

interface AddStudentDialogProps {
    open: boolean;
    onClose: () => void;
    onSubmit: (data: StudentFormData) => void;
}

const AddStudentDialog = ({ open, onClose, onSubmit, enrollmentStatusOptions, enrollmentTypeOptions, advisorOptions }: AddStudentDialogProps) => {
    const [formData, setFormData] = useState<StudentFormData>(initialFormData);
    const [errors, setErrors] = useState<Record<string, string>>({});
    const theme = useTheme();
    const fullScreen = useMediaQuery(theme.breakpoints.down('md'));

    // 处理表单字段变化
    const handleChange = (field: keyof StudentFormData, value: string) => {
        setFormData((prev) => ({
            ...prev,
            [field]: value
        }));

        // 清除错误
        if (errors[field]) {
            setErrors((prev) => {
                const newErrors = { ...prev };
                delete newErrors[field];
                return newErrors;
            });
        }
    };

    // 表单验证
    const validateForm = (): boolean => {
        const newErrors: Record<string, string> = {};
        let isValid = true;

        // 验证必填字段 - 只检查学生ID
        if (!formData.sid) {
            newErrors.sid = '学生ID不能为空';
            isValid = false;
        }

        // 如果有填写邮箱，则验证格式
        if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
            newErrors.email = '请输入有效的邮箱地址';
            isValid = false;
        }

        // 如果有填写手机号，则验证格式
        if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
            newErrors.phone = '请输入有效的手机号码';
            isValid = false;
        }

        // 如果有填写紧急联系人电话，则验证格式
        if (formData.emergency_contact_phone && !/^1[3-9]\d{9}$/.test(formData.emergency_contact_phone)) {
            newErrors.emergency_contact_phone = '请输入有效的手机号码';
            isValid = false;
        }

        // 如果有填写导师电话，则验证格式
        if (formData.academic_advisor_phone && !/^1[3-9]\d{9}$/.test(formData.academic_advisor_phone)) {
            newErrors.academic_advisor_phone = '请输入有效的手机号码';
            isValid = false;
        }

        setErrors(newErrors);
        return isValid;
    };

    // 处理表单提交
    const handleSubmit = () => {
        if (validateForm()) {
            // 获取当前登录用户的uid
            const userInfo = localStorage.getItem('userInfo');
            let uid = '';

            if (userInfo) {
                try {
                    const parsedUserInfo = JSON.parse(userInfo);
                    uid = parsedUserInfo.uid || '';
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }

            // 调用onSubmit传递数据，自动附加uid
            onSubmit({
                ...formData,
                uid
            });

            // 重置表单
            setFormData(initialFormData);
        }
    };

    // 处理取消
    const handleCancel = () => {
        setFormData(initialFormData);
        setErrors({});
        onClose();
    };

    // 渲染表单字段
    const renderField = (field: { id: string; label: string; type: string; description: string; required: boolean }) => {
        const fieldId = field.id as keyof StudentFormData;
        if (field.type === 'select') {
            return (
                <Box>
                    <InputLabel htmlFor={fieldId}>{field.label}</InputLabel>
                    <Select
                        id={fieldId}
                        // label={field.label}
                        fullWidth
                        variant="outlined"
                        size="small"
                        value={formData[fieldId]}
                        onChange={(e) => handleChange(fieldId, e.target.value)}
                        error={!!errors[fieldId]}
                        required={field.required}
                        sx={{ borderRadius: 1 }}
                    >
                        {field.options?.map((option) => (
                            <MenuItem key={option.value} value={option.value}>
                                {option.label}
                            </MenuItem>
                        ))}
                    </Select>
                </Box>
            );
        }

        return (
            <Box>
                <InputLabel htmlFor={fieldId}>{field.label}</InputLabel>
                <TextField
                    id={fieldId}
                    // label={field.label}
                    fullWidth
                    variant="outlined"
                    size="small"
                    value={formData[fieldId]}
                    onChange={(e) => handleChange(fieldId, e.target.value)}
                    error={!!errors[fieldId]}
                    helperText={errors[fieldId]}
                    required={field.required}
                    // placeholder={`请输入${field.label}`}
                    sx={{ borderRadius: 1 }}
                />
            </Box>
        );
    };

    return (
        <Dialog
            open={open}
            onClose={onClose}
            maxWidth="md"
            fullWidth
            fullScreen={fullScreen}
            slotProps={{
                paper: {
                    sx: {
                        borderRadius: 2,
                        boxShadow: '0 12px 28px rgba(0,0,0,0.15)',
                        overflow: 'hidden'
                    }
                }
            }}>
            <DialogTitle
                sx={{
                    p: 2,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    bgcolor: 'primary.main',
                    color: 'white'
                }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <PersonAddAltIcon sx={{ mr: 1 }} />
                    <Typography variant="h6" component="div" sx={{ fontWeight: 500 }}>
                        添加学生信息
                    </Typography>
                </Box>
                <IconButton
                    aria-label="close"
                    onClick={handleCancel}
                    sx={{
                        color: 'white',
                        '&:hover': {
                            backgroundColor: 'rgba(255,255,255,0.1)'
                        }
                    }}>
                    <CloseIcon />
                </IconButton>
            </DialogTitle>

            <DialogContent sx={{ p: 3 }}>
                <Box sx={{ mt: 2 }}>
                    <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 2 }}>
                        {getFormFields(enrollmentStatusOptions, enrollmentTypeOptions, advisorOptions).map((field) => (
                            <Box key={field.id}>{renderField(field)}</Box>
                        ))}
                    </Box>
                </Box>
            </DialogContent>

            <Divider />

            <DialogActions sx={{ px: 3, py: 2, justifyContent: 'flex-end' }}>
                <Button
                    onClick={handleCancel}
                    variant="outlined"
                    sx={{
                        borderRadius: 1.5,
                        px: 3,
                        py: 0.75
                    }}>
                    取消
                </Button>
                <Button
                    onClick={handleSubmit}
                    variant="contained"
                    color="primary"
                    sx={{
                        borderRadius: 1.5,
                        px: 3,
                        py: 0.75,
                        boxShadow: '0 4px 10px rgba(0, 0, 0, 0.1)',
                        '&:hover': {
                            boxShadow: '0 6px 12px rgba(0, 0, 0, 0.15)'
                        }
                    }}>
                    提交
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default AddStudentDialog;
